package com.netty.handler;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author suzhen
 * @create 2018/7/11
 */
public class HttpChannelHandler extends ChannelInitializer<SocketChannel> {


    public HttpChannelHandler() {
    }

    @Override
    protected void initChannel(SocketChannel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        //解决解决半包读问题
        //pipeline.addLast(new LineBasedFrameDecoder(1024));
        //pipeline.addLast(new StringDecoder());
        // HTTP请求的解码和编码
        pipeline.addLast(new HttpServerCodec());
        // 把多个消息转换为一个单一的FullHttpRequest或是FullHttpResponse，
        // 原因是HTTP解码器会在每个HTTP消息中生成多个消息对象HttpRequest/HttpResponse,HttpContent,LastHttpContent
        pipeline.addLast(new HttpObjectAggregator(65536));
        // 主要用于处理大数据流，比如一个1G大小的文件如果你直接传输肯定会撑暴jvm内存的; 增加之后就不用考虑这个问题了
        //向客户端发送HTML5文件
        pipeline.addLast(new ChunkedWriteHandler());
        // 业务代码
        pipeline.addLast(new HttpRequestHandler());
    }
}
